package com.example.gate.grpc;

import com.example.common.grpc.GrpcMessageBuilder;
import com.example.common.grpc.ServerIdGenerator;
import com.example.game.CResp;
import com.example.game.LoginResponse;
import com.example.game.proto.internal.*;
import com.example.gate.net.AccountSession;
import com.example.gate.net.SessionGroup;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Gate服务的gRPC服务实现
 *
 * @author: Allen
 * @create: 2025/7/3 16:43
 * @description: 处理来自其他服务的gRPC请求
 **/
@Slf4j
@GrpcService
@Service
public class GrpcServiceImpl extends GrpcServiceGrpc.GrpcServiceImplBase {

    @Autowired
    private SessionGroup sessionGroup;

    @Autowired
    private ServerIdGenerator serverIdGenerator;

    @Override
    public void heartbeat(SrvReq request, StreamObserver<SrvResp> responseObserver) {
        SrvResp build = SrvResp.newBuilder().setRet(0).build();
        responseObserver.onNext(build);
        responseObserver.onCompleted();
    }

    @Override
    public void process(SrvReq request, StreamObserver<SrvResp> responseObserver) {
        try {
            log.info("收到处理请求: id={}, code={}, sid={}, userId={}",
                    request.getId(), request.getCode(), request.getSid(),
                    request.getUserId());

            SrvResp response = handleProcessRequest(request);
            responseObserver.onNext(Objects.requireNonNullElseGet(response, () -> GrpcMessageBuilder.buildSuccessResp(serverIdGenerator.getServerId(), request.getCode())));
            responseObserver.onCompleted();
            log.debug("处理请求响应发送成功: id={}, code={}", request.getId(), request.getCode());
        } catch (Exception e) {
            log.error("处理请求失败: id={}, code={}", request.getId(), request.getCode(), e);

            SrvResp errorResponse = GrpcMessageBuilder.buildErrorRespFromReq(
                    request, -1, "Gate service error: " + e.getMessage());

            responseObserver.onNext(errorResponse);
            responseObserver.onCompleted();
        }
    }

    /**
     * 根据协议号处理不同的业务逻辑
     *
     * @param request 请求消息
     * @return 响应消息
     */
    private SrvResp handleProcessRequest(SrvReq request) {
        int code = request.getCode();

        switch (code) {
            case 2002:
               return   handleUserLogin1(request);
            default:


                log.warn("未知的协议号: code={}", code);
                return GrpcMessageBuilder.buildErrorRespFromReq(
                        request, -1001, "Unknown protocol code: " + code);
        }
    }

    private SrvResp handleUserLogin1(SrvReq request) {

        try {
            LoginResponse response = LoginResponse.parseFrom(request.getBody());
            log.info("处理用户登录返回: userId={},name:{}", request.getUserId(),response.getUserInfo().getUsername());
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException(e);
        }
        AccountSession accountSession = sessionGroup.getAccountSession(request.getUserId());
        if (accountSession!=null) {
            CResp cResp = CResp.newBuilder().setRet(0).setCode(request.getCode()).setBody(request.getBody()).build();
            accountSession.getChannel().writeAndFlush(cResp);
        }
        return GrpcMessageBuilder.buildSuccessResp(request.getSid(), request.getCode());
    }

}
